package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.pojo.Announcement;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.pojo.MessageCommentVo;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.AnnouncementVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.UserInfoVo;
import com.tanhua.server.vo.UsersVo;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/7/5 20:52
 */

@Service
public class IMService {

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private AnnouncementService announcementService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 根据HuanXinUserId,查询HuanXinUser ,封装UserInfo:
     *
     * @param userName
     * @return
     */
    public UserInfoVo queryUserInfoByHuanXinId(String userName) {
        HuanXinUser huanXinUser = huanXinApi.queryHuanXinUserByUserName(userName);
        if (ObjectUtil.isEmpty(huanXinUser)) {
            return null;
        }

        //封装userInfo：
        //查询用户信息
        UserInfo userInfo = this.userInfoService.queryTodayBestInfo(huanXinUser.getUserId());
        //只传一个userId:只查一个userInfo
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);

        return userInfoVo;
    }

    /**
     * 添加好友：
     *
     * @param friendId
     * @return
     */
    public boolean contactsFriends(Integer friendId) {

        User user = UserThreadLocal.get();

        Boolean aBoolean = usersApi.addFriends(user.getId(), Long.valueOf(friendId));

        if (aBoolean) {
            //添加数据库表成功：再注册环信好友：
            return huanXinApi.addFriends(user.getId(), Long.valueOf(friendId));
        }

        return false;
    }

    /**
     * 查询联系人列表：
     *
     * @param page
     * @param pageSize
     * @param keyword
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        User user = UserThreadLocal.get();

        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        List<Users> usersList;
        if (StrUtil.isNotEmpty(keyword)) {
            //查询全部，再进行关键字过滤：
            usersList = usersApi.queryAllUsers(user.getId(), keyword);
        } else {
            //分页查询：
            PageInfo<Users> pageInfo = usersApi.queryUsersByPage(user.getId(), page, pageSize);
            usersList = pageInfo.getRecords();
        }
        if (usersList.size() == 0) {
            return pageResult;
        }

        //获取所有的friendId;
        List<Object> friendIds = new ArrayList<>();
        for (Users users : usersList) {
            friendIds.add(users.getFriendId());
        }

        //根据friendsId查询所有的userInfo:
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", friendIds);
        if (StrUtil.isNotEmpty(keyword)) {
            queryWrapper.like("nick_name", keyword);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryRecommendationUserInfo(queryWrapper);
        List<UsersVo> contactsList = new ArrayList<>();
        //填充用户信息
        UsersVo usersVo;
        for (UserInfo userInfo : userInfoList) {
            usersVo = new UsersVo();
            usersVo.setId(userInfo.getUserId());
            usersVo.setAge(userInfo.getAge());
            usersVo.setAvatar(userInfo.getLogo());
            usersVo.setGender(userInfo.getSex().name().toLowerCase());
            usersVo.setNickname(userInfo.getNickName());
            //环信用户账号
            usersVo.setUserId("HX_" + String.valueOf(userInfo.getUserId()));
            usersVo.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));
            contactsList.add(usersVo);
        }
        pageResult.setItems(contactsList);

        return pageResult;
    }

    /**
     * 查询评论列表消息：
     *
     * @param commentType
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryCommentList(String commentType, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();

        CommentType commentType1 = null;
        switch (commentType) {
            case "likes":
                commentType1 = CommentType.LIKE;
                break;
            case "loves":
                commentType1 = CommentType.LOVE;
                break;
            case "comments":
                commentType1 = CommentType.COMMENT;
                break;
            default:
                return null;
        }

        PageInfo<Comment> pageInfo = quanZiApi.queryCommentListByUser(user.getId(), commentType1, page, pageSize);

        List<Comment> records = pageInfo.getRecords();
        if (records.size() == 0) {
            return pageResult;
        }

        //评论人的userId:
        List<Object> ids = new ArrayList<>();
        for (Comment record : records) {
            ids.add(record.getUserId());
        }
        //根据ids去查询userInfo:
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(ids);
        //userId  与 userInfo的一一对应关系：
        Map<Long, UserInfo> map = new HashMap<>();
        for (UserInfo userInfo : userInfos) {
            map.put(userInfo.getUserId(), userInfo);
        }
        //封装对象：
        List<MessageCommentVo> messageCommentVos = new ArrayList<>();
        MessageCommentVo messageCommentVo = null;
        for (Comment record : records) {
            messageCommentVo = new MessageCommentVo();
            messageCommentVo.setId(new ObjectId().toHexString());
            messageCommentVo.setAvatar(map.get(record.getUserId()).getLogo());
            messageCommentVo.setNickname(map.get(record.getUserId()).getNickName());
            messageCommentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "yyyy-MM-dd HH:mm"));
            messageCommentVos.add(messageCommentVo);
        }

        pageResult.setItems(messageCommentVos);

        return pageResult;
    }

    /**
     * 查询公告：
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageAnnoucementList(Integer page, Integer pageSize) {

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        IPage<Announcement> announcementIPage = announcementService.queryAnnouncementList(page, pageSize);

        List<Announcement> records = announcementIPage.getRecords();
        if (records.size() == 0) {
            return pageResult;
        }

        List<AnnouncementVo> announcementVoList = new ArrayList<>();

        AnnouncementVo announcementVo = null;
        for (Announcement record : records) {
            announcementVo = new AnnouncementVo();
            announcementVo.setId(record.getId().toString());
            announcementVo.setTitle(record.getTitle());
            announcementVo.setDescription(record.getDescription());
            announcementVo.setCreateDate(DateUtil.format(record.getCreated(), "yyyy-MM-dd HH:mm"));
            announcementVoList.add(announcementVo);
        }
        pageResult.setItems(announcementVoList);
        return pageResult;
    }


    /**
     * 删除环信好友关系：
     * @param id
     * @param deleteUserId
     */
    public Boolean deleteUser(Long id, Long deleteUserId) {
        return huanXinApi.removeFriends(id,deleteUserId);
    }
}
